<template>
  <div class="my-date-picker">
    <el-date-picker
      v-model="time"
      :picker-options="options"
      :default-time="defaultTime"
      type="datetimerange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      value-format="yyyy-MM-dd HH:mm:ss"
      @focus="getDefaultTime"
      @change="datePickerChange"
      v-on="$listeners"
      v-bind="$attrs"
    >
    </el-date-picker>
  </div>
</template>

<script>
export default {
  name: "my-date-picker",
  props: {
    value: {
      required: true,
      default: () => [],
    },
  },
  model: {
    prop: "value",
    event: "update",
  },
  data() {
    return {
      time: this.value,
      options: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 1000 * 60 * 60 * 24;
        },
      },
      defaultTime: [],
    };
  },
  watch: {
    value(val) {
      this.time = val;
    },
  },
  methods: {
    getDefaultTime() {
      this.$emit("focus");
      let d = new Date();
      let year, month, day, hour, minute;
      //当前时间的十分钟后
      d.setTime(d.getTime() + 10 * 60 * 1000);
      [year, month, day, hour, minute] = [
        d.getFullYear(),
        d.getMonth(),
        d.getDate(),
        d.getHours(),
        d.getMinutes(),
      ];
      //选中开始时间时的默认值为当前时间的十分钟后
      //选中结束时间时的默认值为当前时间的一个小时十分钟后
      this.defaultTime = [
        hour + ":" + minute + ":00",
        23 + ":" + 59 + ":" + 59,
      ];
    },
    datePickerChange(value) {
      this.$emit("change", value);
      if (value) {
        const time = value[0];
        if (new Date(time).getTime() < Date.now()) {
          this.time = [];
          this.$message.error("不能在当前时间之前");
        }
      }
      this.$emit("update", this.time);
    },
  },
};
</script>

<style scoped>
.my-date-picker {
  width: 100%;
}
</style>
